<?php
namespace Home\Controller;
use Think\Controller;

class PayreportController extends PaycommonController { 
    //支付方式页---post形式
    public function info(){
        //是否登录认证
        $check_result = $this->checkBuyUser();

        if($check_result['status']!=200){
            switch($check_result['status']){
                case 4002:
                    $this->error('请认证','/');
                    break;
                case 4003:
                    $this->error('请登录云途用户帐号购买','/');
                    break;
                default:
                    $this->error('请登录','/member/login.html');
                    break;
            }
        }
        $id = I('post.id',0,'intval');

        if(is_numeric($id) && $id){
            $ReportModel = D('Report');

            //获取报告信息
            $info = $ReportModel->info($id);
            if(!empty($info)){
                $price = $info['price'];

                if($price > 0){
                    $this->assign('info',$info);
                    $this->display();    
                }else{
                    //免费情况下，转至下载处理
                    $this->error("该报告已免费","/report/detail.html?id=".$id);
                }
            }else{
               $this->error("报告不存在",'/report/index.html'); 
            }

        }else{
            $this->error("报告不存在",'/report/index.html');
        }
        
    }

    //重新支付
    public function keeppay(){
        //是否登录认证
        $check_result = $this->checkBuyUser();
        if($check_result['status']!=200){
            switch($check_result['status']){
                case 4002:
                    $this->error('请认证','/');
                    break;
                case 4003:
                    $this->error('请登录云途用户帐号购买','/');
                    break;
                default:
                    $this->error('请登录','/');
                    break;
            }
        }

        //检查订单是否存在
        $order_id = I('post.order_id',null);
        if(!empty($order_id)){
            //获取订单信息
            $orderModel = D('ReportOrders');
            $order_info = $orderModel->getInfo($order_id);

            //是否该用户
            if($this->uid!=$order_info['uid']){
                $this->error('您无权限支付该订单','/');
            }
            //是否已支付
            if(in_array($order_info['pay_status'],array(1,2))){
                $this->error('该订单已支付成功','/'); 
            }

            //检查该订单中价格是否对应现有商品价格，如果不对应则重新下单
            $reportModel = D('Report');
            $report_info = $reportModel->info($order_info['report_id']);
            $report_status = $report_info['status'];
            $report_src_price = $report_info['price'];
            if($report_status!=1) $this->error("该报告已下架","/report/index.html");
            if($report_src_price != $order_info['amount']) $this->error('该报告价格已改变，请重新购买',"/report/detail.html?id=".$order_info['report_id']);
			
            $this->assign('info',$order_info);
            $this->display('keeppay');

        }else{
            $this->error("该报告已下架","/report/index.html");
        }
    }

    //付费API下单（支付方式下一步动作）
    public function pay(){
        //是否登录认证
        $this->checkBuyUser($isAjax=true);

        //获取报告id
        $report_id = I('post.id',0,'intval');
        // 平台类型
        $pay_platform = I('post.platform',1,'intval');

        //获取报告信息--是否下线，是否免费
        $reportModel = D('Report');
        $info = $reportModel->info( (int)$report_id);
        //是否可用
        if($info['status'] != 1 ){
            $this->error("该报告已下线",'/');
        }

        //改报告是否免费
        if($info['price']  > 0){
            //是否已购买
            $reportOrdersModel = D('ReportOrders');
            $order_history = $reportOrdersModel->checkExistsBuy($this->uid,$report_id);
            if(!empty($order_history)){
                redirect('已购买，请转至个人中心下载','/user/index.html');
            }
            if($pay_platform==1){
                $pay_platform_name = "支付宝";
            }else if($pay_platform==2){
                $pay_platform_name = "微信平台";
            }
            $order_data = $this->getOrderData($report_id,$pay_platform);
            $order_result = $reportOrdersModel->writeOrder($order_data);
            
            if(!$order_result){
                $destination = C('LOG_PATH').'order_faild/'.date('y_m_d').'.log';
                $message = "下单失败-".$order_data['report_title']."-".$report_id."-".$this->uid."-".$pay_platform_name."-".date('Y-m-d H:i:s');
                $level = \Think\Log::ERR;
            }else{
                $destination = C('LOG_PATH').'order_success/'.date('y_m_d').'.log';
                $message = "下单成功-".$order_data['report_title']."-".$report_id."-".$this->uid."-".$pay_platform_name."-".date('Y-m-d H:i:s');
                $level = \Think\Log::INFO;
            }
            \Think\Log::write($message,$level,$type='',$destination);

            if($order_result){
                if($pay_platform==1){
                    $this->alipay($order_data);//支付宝
                }else if($pay_platform==2){
                    $this->wxpay($order_data);//微信支付
                }
            }else{
                $this->error("系统异常",'/');
            }

        }else if ($info['api_is_charge']==0){
            $this->error("该报告已免费",'/report/index.html?id='.$report_id);
        }

    }

    //继续支付下一步
    public function repay(){
        //是否登录认证
        $this->checkBuyUser($isAjax=true);

        $pay_platform = I('post.platform',1,'intval');
        if( !in_array( $pay_platform,array(1,2) ) ){
            $this->error('暂不支持改支付平台','/');
        }
        $order_id = I('post.order_id',null);
        if(empty($order_id)){
            $this->error('缺失必要参数','/');   
        }

        //查看订单
        $orderModel = D('ReportOrders');
        $order_info = $orderModel->getInfo($order_id);

        //直接支付
        if(!empty($order_info)){
            //是否该用户，是否已支付
            if( in_array($order_info['pay_status'],array(1,2) ) ){
                $this->error('该订单已支付成功','/');
            }
            if($pay_platform==1){
                $pay_platform_name = "支付宝";
            }else if($pay_platform==2){
                $pay_platform_name = "微信平台";
            }
            $destination = C('LOG_PATH').'repay_order/'.date('y_m_d').'.log';
            $message = "重新支付-".$order_info['report_title']."-".$order_info['order_id']."-"."-".$order_info['uid']."-".$pay_platform_name."-".date('Y-m-d H:i:s');
            $level = \Think\Log::INFO;
            \Think\Log::write($message,$level,$type='',$destination);

            if($pay_platform==1){
                $this->alipay($order_info);//支付宝
            }else if($pay_platform==2){
                $this->wxpay($order_info);//微信支付
            }
        }else{
            $this->error("该订单不存在",'/');
        }
    }

    //阿里支付页
    private function alipay($info){
        header("Content-type:text/html;charset=utf-8");
        Vendor('Pay.alipay.alipay_submit','','.class.php');

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $info['order_id'];

        //订单名称，必填
        $subject = $info['report_title'];

        //付款金额，必填
        $total_fee = $info['amount'];

        //商品描述，用户邮箱-uid-购买产品类型（1：API；2：报告）
        $body = $info['user_name']."-".$info['uid']."-2";

        /************************************************************/
        //构造要请求的参数数组，无需改动
        $parameter = array(
                "service"       => C(SERVICE),
                "partner"       => C(PARTNER),
                "seller_id"  => C(SELLER_ID),
                "payment_type"  => C(PAYMENT_TYPE),
                "notify_url"    => C(NOTIFY_URL),
                "return_url"    => C(RETURN_URL),
                "anti_phishing_key"=>C(ANTI_PHISHING_KEY),
                "exter_invoke_ip"=>C(EXTER_INVOKE_IP),
                "out_trade_no"  => $out_trade_no,
                // "subject"   => mb_convert_encoding($subject, 'utf-8', 'gb2312'),
                "subject"  =>$subject,
                "total_fee" => $total_fee,
                "body"  => "",
                "extra_common_param"=>$body,
                "_input_charset"    => C(INPUT_CHARSET),
                
        );
        $alipaySubmit = new \AlipaySubmit($this->alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "SUBMIT");

        echo $html_text;
        return true;
    }

    //微信支付页
    private function wxpay($info){
        //模式二
        /**
         * 流程：
         * 1、调用统一下单，取得code_url，生成二维码
         * 2、用户扫描二维码，进行支付
         * 3、支付完成之后，微信服务器会通知支付成功
         * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
         */
        ini_set('date.timezone','Asia/Shanghai');
        error_reporting(E_ERROR);
        Vendor('Pay.wxpay.WxPay#Api','','.php');
        Vendor('Pay.wxpay.WxPay#NativePay','','.php');
        Vendor('Pay.wxpay.log','','.php');
        $notify = new \NativePay();

        $input = new \WxPayUnifiedOrder();

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $info['order_id'];

        //订单名称，必填
        $subject = $info['report_title'];

        //付款金额，必填
        $total_fee = $info['amount'];

        //商品描述，用户邮箱-uid-购买产品类型（1：API；2：报告）
        $body = $info['user_name']."-".$info['uid']."-2";

        $input->SetBody($subject);
        $input->SetAttach($body);
        // $input->SetOut_trade_no(C('WEIXINPAY_CONFIG.MCHID').date("YmdHis"));
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($info['service_name']);
        $input->SetNotify_url(C('WEIXINPAY_CONFIG.NOTIFY_URL'));
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($info['api_id']);
        $result = $notify->GetPayUrl($input,$timeout=600);

        if($result['return_code']!='FAIL'){
            $this->assign('qrcode',$result["code_url"]);

            $all_package = json_decode($info['condition_json'],true);
            $this->assign('subject',$subject);
            $this->assign('total_fee',$total_fee);
            $this->assign('cycle',$all_package['package_cycle']);
            $this->assign('out_trade_no',$out_trade_no);

            $this->display('wxinfo');
        }else{
            $this->error($result['return_msg'],'/report/detail.html?id='.$info['report_id']);
        }

    }

    //微信支付成功后页面-自己程序跳转
    public function wxpay_return(){
        header("Content-type:text/html;charset=utf-8");
        $order_id = I('get.orderid');
        $orderModel = M('ReportOrders');
        $order_info = $orderModel->where("order_id='".$order_id."'")->find();
        if(empty($order_info) ){
           //更新订单状态
           error('改订单不存在');
        }
        
        $this->assign('amount',$order_info['amount']);
        $this->display('success');

    }

    //微信查询订单结果
    public function wxquery(){
        $out_trade_no = I('post.id',0,'trim');

        if(empty($this->uid)){
            $this->ajaxReturn( array('status'=>4003,'msg'=>'请登录','data'=>null));
        }
        if(empty($out_trade_no)){
            $this->ajaxReturn( array('status'=>4004,'msg'=>'缺少必要参数','data'=>null));
        }

        $orderModel = D('ReportOrders');
        $result = $orderModel->wxOrderResult($out_trade_no);
        if($result){
            $this->ajaxReturn( array('status'=>200,'msg'=>'OK','data'=>null));
        }else{
            $this->ajaxReturn( array('status'=>4005,'msg'=>'暂未支付','data'=>null));  
        }
    }

    //根据报告编号，编辑订单入库信息
    public function getOrderData($report_id,$pay_platform=1){
        $reportModel = D('Report');
        $info = $reportModel->info($report_id);
        if(empty($info)) return null;

        $data = array();
        $data['order_id'] = gorderid();
        $data['report_title'] = $info['title'];
        $data['report_id'] = $info['id'];
        $data['amount'] = $info['price'];
        $data['uid'] = $this->uid;//购买者uid
        $data['works_uid'] = $info['uid'];//报告拥有者uid
        $data['user_name'] = $this->user_email;
        $data['order_time'] = time();
        $data['pay_platform'] = $pay_platform;
        return $data;
    }


}